//
//  HandPickTableViewController.m
//  老司机发车了
//
//  Created by SuperNing on 16/8/6.
//  Copyright © 2016年 斌. All rights reserved.
//

#import "HandPickTableViewController.h"

#import "HandPickCarouselModel.h"
#import "HandPickRecommendModel.h"
#import "HandPickMusicListModel.h"
#import "RecommendTableViewCell.h"

#import "DetailSongTableViewController.h"

@interface HandPickTableViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

// 轮播图
@property (nonatomic, strong) UIScrollView *headScrollView;
// 轮播图数据模型
@property (nonatomic, strong) NSMutableArray *imgArray;

@property (nonatomic, strong)UIPageControl* pageCtr;
// 轮播图的坐标
@property (nonatomic)NSInteger index;
// 定时器时间
@property (nonatomic, strong)NSTimer* timer;

// 精品推荐数据模型
@property(nonatomic, strong) NSMutableArray *recommendArray;

// 精品歌单数据模型
@property(nonatomic, strong) NSMutableArray *musicListArray;

@property (nonatomic, strong) UIScrollView *firstSectionView;

@end

@implementation HandPickTableViewController

- (NSMutableArray *)imgArray{
    
    if (!_imgArray) {
        _imgArray = [[NSMutableArray alloc] init];
    }
    return _imgArray;
}

- (NSMutableArray *)musicListArray{
    if (!_musicListArray) {
        _musicListArray = [[NSMutableArray alloc] init];
    }
    return _musicListArray;
}

- (NSMutableArray *)recommendArray{
    if (!_recommendArray) {
        _recommendArray = [[NSMutableArray alloc] init];
    }
    return _recommendArray;
}

- (UIScrollView *)firstSectionView{
    
    if (!_firstSectionView) {
        _firstSectionView = [[UIScrollView alloc] init];
    }
    return _firstSectionView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self analyseImgData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:@"RCell"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self analyseFirstSectionData];
    [self analyseSecondSectionData];
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurView.frame = self.view.bounds;
    
    self.tableView.backgroundView = blurView;
    
    
    self.view.ownHeight = self.view.ownHeight - 108;
    
    
}

#pragma mark-----滚动头视图
- (void)analyseImgData{
    
    [NetWorkRequestManager requestWithType:POST urlString:HandPickCarousel_Url parDic:@{} finish:^(NSData *data) {
       
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *dict in dataDic[@"pic"]) {
            HandPickCarouselModel *model = [[HandPickCarouselModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.imgArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self addHeadView];
            self.tableView.tableHeaderView = self.headScrollView;

//            [self.tableView reloadData];
        });
        
    } finishError:^(NSError *error) {
        
    }];
}

- (void)addHeadView{
    
    self.headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenWidth * 0.5)];
    self.headScrollView.showsVerticalScrollIndicator = NO;
    self.headScrollView.showsHorizontalScrollIndicator = NO;
    self.headScrollView.bounces = YES;
    self.headScrollView.pagingEnabled = YES;
    self.headScrollView.delegate = self;
    
    [self.imgArray addObject:[self.imgArray firstObject]];
    
    [self.imgArray insertObject:self.imgArray[self.imgArray.count - 2] atIndex:0];
    
    self.headScrollView.contentSize = CGSizeMake(screenWidth * _imgArray.count, screenWidth * 0.5);
    self.headScrollView.contentOffset = CGPointMake(screenWidth, 0);
    
    for (NSInteger i = 0; i < self.imgArray.count; i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i * screenWidth, 0, screenWidth, self.headScrollView.ownHeight)];
        HandPickCarouselModel *model = self.imgArray[i];
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.randpic]];
        [self.headScrollView addSubview:imgView];
    }
    
    _pageCtr = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _headScrollView.endY - 20, screenWidth, 20)];
    _pageCtr.numberOfPages = _imgArray.count - 2;
    [self.headScrollView addSubview:_pageCtr];
    
    [self setupTimer];
}

- (void)setupTimer{
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
}

- (void)timeAction:(NSTimer *)timer{
    
    _index++;
    [_headScrollView setContentOffset:CGPointMake(screenWidth * (_index + 1), 0) animated:YES];
    if (_index == self.imgArray.count - 2) {
        _index = 0;
    }
    _pageCtr.currentPage = _index;

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageCtr.currentPage = scrollView.contentOffset.x / screenWidth - 1;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGPoint offset = scrollView.contentOffset;
    
    self.index = offset.x / screenWidth - 1;
    NSInteger num = _imgArray.count - 2;
    
    if (offset.x > (num + 0.5) *screenWidth) {
        self.headScrollView.contentOffset = CGPointMake(offset.x - num * screenWidth, 0);
    }
    
    if (offset.x < 0.5 *screenWidth) {
        self.headScrollView.contentOffset = CGPointMake(offset.x + num * screenWidth, 0);
    }
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [_timer invalidate];
    _timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self setupTimer];
}

#pragma mark-----各分区标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"精品推荐";
    }else{
        return @"精品歌单";
    }
}

#pragma mark-----第一个分区内容

- (void)analyseFirstSectionData{
    
    [NetWorkRequestManager requestWithType:POST urlString:HandPickRecommend_Url parDic:@{} finish:^(NSData *data) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = dataDic[@"content"][@"list"];
        
        for (NSDictionary *dict in dataArr) {
            HandPickRecommendModel *model = [[HandPickRecommendModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.recommendArray addObject:model];
        }
        
        
    } finishError:^(NSError *error) {
        
    }];
}


- (void)addFirstSectionView{
    
    self.firstSectionView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenWidth / 3.f + 20)];
    self.firstSectionView.backgroundColor = [UIColor clearColor];
    
    self.firstSectionView.contentSize = CGSizeMake(screenWidth * 2, 0);
    _firstSectionView.showsVerticalScrollIndicator = NO;
    _firstSectionView.showsHorizontalScrollIndicator = NO;
    _firstSectionView.pagingEnabled = YES;
    
    CGFloat margin = screenWidth / 12.f;
    CGFloat width = screenWidth / 3.f;
    for (NSInteger i = 0; i < self.recommendArray.count; i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake((i * 2 + 1) * margin + width * i, 10, width, width)];
        HandPickRecommendModel *model = self.recommendArray[i];
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.pic]];
        imgView.layer.cornerRadius = width / 2;
        imgView.layer.masksToBounds = YES;
        
        imgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        imgView.tag = i;
        [imgView addGestureRecognizer:tap];
        
        [self.firstSectionView addSubview:imgView];
    }

}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    NSInteger i = tap.view.tag;
    
    HandPickRecommendModel *model = self.recommendArray[i];
    DetailSongTableViewController *detailVC = [[DetailSongTableViewController alloc] init];
    detailVC.picUrl = model.pic;
    detailVC.listid = model.listid;
    detailVC.jsonNum = 0;

    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark-----第二个分区内容

- (void)analyseSecondSectionData{
    
    [NetWorkRequestManager requestWithType:POST urlString:HandPickMusicList_Url parDic:@{} finish:^(NSData *data) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *dict in dataDic[@"content"]) {
            HandPickMusicListModel *model = [[HandPickMusicListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.musicListArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [self.tableView reloadData];
        
        });
        
    } finishError:^(NSError *error) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return _musicListArray.count;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return screenWidth / 3.f + 20;
    } else {
        return 120;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.section == 0) {
        
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        
        [self addFirstSectionView];
        [cell addSubview:self.firstSectionView];
        
        cell.backgroundColor = [UIColor clearColor];
        return cell;
        
    } else {
        RecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RCell" forIndexPath:indexPath];
        HandPickMusicListModel *model = self.musicListArray[indexPath.row];
        [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.pic_300]];
        cell.singerName.text = model.title;
        cell.descLabel.text = model.desc;
        
        cell.backgroundColor = [UIColor clearColor];
        return cell;

    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailSongTableViewController *detailVC = [[DetailSongTableViewController alloc] init];
    HandPickMusicListModel *model = self.musicListArray[indexPath.row];
    detailVC.picUrl = model.pic_300;
    detailVC.listid = model.listid;
    
    detailVC.jsonNum = 0;
    [self.navigationController pushViewController:detailVC animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
